package com.rfid.afd.presenter;

import android.os.Handler;

import com.rfid.afd.activity.listener.ModelListener;
import com.rfid.afd.activity.view.IDeleteView;
import com.rfid.afd.model.DeleteModel;
import com.rfid.db.bean.Rfid;
import com.rfid.util.RfidManager;
import com.rfid.util.DBManager;

import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class DeletePresenter extends BasePresenter<IDeleteView> implements ModelListener {

    DeleteModel mDeleteModel;
    protected ExecutorService mExecutor;
    protected Handler mHandler;

    public DeletePresenter() {
        mHandler = new Handler();
        mExecutor = Executors.newSingleThreadExecutor();
        mDeleteModel = new DeleteModel();
        mDeleteModel.setRfidListener(this);
    }

    public void startScanRfid() {
        mDeleteModel.startScan();
    }

    public void stopScanRfid() {
        mDeleteModel.stopScan();
    }

    public void delete(List<Rfid> rfids) {//删除记录，同步服务器数据库
        if(rfids.size() > 0) {
            mDeleteModel.deleteRfids(rfids);
            mIview.onDeleteComplete(rfids);
        }
    }

    public void queryRfidsByBookName(String name) {
        mExecutor.execute(new Runnable() {
            @Override
            public void run() {
                List<Rfid> data = mDeleteModel.getRfidsByBookName(name);
                mHandler.post(new Runnable() {
                    @Override
                    public void run() {
                        if(mIview != null)
                             mIview.onRfidsByBookName(data);
                    }
                });
            }
        });
    }

    public void queryDeleteRfids() {
        mExecutor.execute(new Runnable() {
            @Override
            public void run() {
                List<Rfid> deletes = mDeleteModel.getRemoteDeleteRfids();
                mHandler.post(new Runnable() {
                    @Override
                    public void run() {
                        if(mIview != null)
                            mIview.onDeleteQuery(deletes);
                    }
                });
            }
        });
    }

    @Override
    public void onRfid(String rfid) {
        Rfid r = DBManager.queryRfidByUid(rfid);
        if(r == null) {
            return;
        }
        mHandler.post(new Runnable() {
            @Override
            public void run() {
                if(mIview != null)
                    mIview.onScanedRfid(rfid,r);
            }
        });
    }

    @Override
    public void onRfid(String epc, String barcode) {
    }
}
